package com.haiyi.activiti.engine.framework.template.freemarker;

import com.haiyi.activiti.engine.exception.StringResolverException;
import com.haiyi.activiti.engine.framework.template.StringResolver;
import com.haiyi.activiti.engine.framework.template.StringResolverEnum;
import freemarker.cache.StringTemplateLoader;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import org.springframework.stereotype.Component;

import java.io.*;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

/**
 * @author:Luhui
 * @qq:729913162
 * @Date:2018/12/9 0009
 * @Time:12:19
 */
@Component
public class FreemarkerResolver implements StringResolver {
    @Override
    public String resolve(String tempStr, Map<String, Object> params) {
        Configuration cfg = new Configuration();
        StringTemplateLoader stringLoader = new StringTemplateLoader();
        stringLoader.putTemplate("myTemplate",tempStr);
        cfg.setTemplateLoader(stringLoader);
        Writer out = null;
        ByteArrayOutputStream byteArrayOutputStream = null;
        try {
            Template temp = cfg.getTemplate("myTemplate","utf-8");
            byteArrayOutputStream = new ByteArrayOutputStream();
            out = new BufferedWriter(new OutputStreamWriter(byteArrayOutputStream));
            temp.process(params,out);
            byte[] bytes = byteArrayOutputStream.toByteArray();
            String result = new String(bytes);
            return result;
        } catch (IOException e) {
            throw new StringResolverException("freemarker解析时io流异常！",e);
        } catch (TemplateException e) {
            throw new StringResolverException("freemarker字符串解析异常！",e);
        }finally {
            if(out != null){
                try {
                    out.close();
                } catch (IOException e) {
                    throw new StringResolverException("freemarker解析时io流异常！",e);
                }
            }
            if (byteArrayOutputStream != null) {
                try {
                    byteArrayOutputStream.close();
                } catch (IOException e) {
                    throw new StringResolverException("freemarker解析时io流异常！",e);
                }
            }
        }
    }

    @Override
    public List<String> getServiceTypes() {
        return Arrays.asList(StringResolverEnum.FREEMARKER.getCode());
    }
}
